import 'package:riki_router/event/riki_event.dart';
import 'package:riki_router/package/abs_riki_package_listener.dart';

export 'package:riki_router/package/abs_riki_package_listener.dart';

abstract class RikiBasePackage implements RikiEventListener {
  String get packageName;

  List<AbsRikiPackageListener> _packageListeners = [];

  /// 添加package分发
  void addPackageListener(AbsRikiPackageListener listener) {
    if (!_packageListeners.contains(listener)) {
      _packageListeners.add(listener);
    }
  }

  /// 解除package分发
  void removePackageListener(AbsRikiPackageListener listener) {
    _packageListeners.remove(listener);
  }

  /// 根据listener类型分发时间
  void fire<T extends AbsRikiPackageListener>(dynamic arguments) {
    _getPackageListeners<T>().forEach((listener) {
      listener.onRikiPackageEvent(arguments);
    });
  }

  /// 获取当前类型的listeners
  List<T> _getPackageListeners<T extends AbsRikiPackageListener>() {
    return _packageListeners.where((element) => element is T).toList().cast<T>();
  }

  void registerRikiEvent() {
    RikiEvent.instance.addListener(packageName, this);
  }

  void unregisterRikiEvent() {
    RikiEvent.instance.removeListener(this);
  }
}
